package service

import (
	"context"
	"lot_admin_api/api"
	"lot_admin_api/internal/consts"
	"lot_admin_api/internal/dao"
	"lot_admin_api/internal/model"
	"lot_admin_api/utility/paging"
	"lot_admin_api/utility/response"

	"github.com/gogf/gf/v2/frame/g"
)

type sCompany struct {
}

var insCompany = sCompany{}

func Company() *sCompany {
	return &insCompany
}

// ApplyCompany 申请/创建公司公司
func (s *sCompany) ApplyCompany(ctx context.Context, req *api.ApplyCompanyReq) (lastInsertId int64, err error) {
	r := g.RequestFromCtx(ctx)
	saveInfo, err := dao.LotCompany.Ctx(ctx).Save(req)
	if err != nil {
		response.JsonExit(r, consts.HTTPInternalServer.Code(), "保存数据失败")
	}
	lastInsertId, err = saveInfo.LastInsertId()
	return lastInsertId, err
}

// CompanyInfo 通过id获取公司详情
func (s *sCompany) CompanyInfo(ctx context.Context, Id int64) (res *model.CompanyDetailsRes, err error) {
	r := g.RequestFromCtx(ctx)
	_ = dao.LotCompany.Ctx(ctx).Where("id", Id).Scan(&res)
	if res == nil {
		response.JsonExit(r, consts.HTTPInternalServer.Code(), "没有该公司")
	}
	return res, err
}

// UpdateCompany 更新公司信息
func (s *sCompany) UpdateCompany(ctx context.Context, req *api.UpdateCompanyReq) (lastInsertId int64, err error) {
	s.searchCompany(ctx, req.Id)
	saveInfo, err := dao.LotCompany.Ctx(ctx).Where("id", req.Id).Update(req)
	_, err = saveInfo.LastInsertId()
	return req.Id, err
}

// DisableCompany 禁用/启用公司信息
func (s *sCompany) DisableCompany(ctx context.Context, req *api.DisableCompanyReq) (lastInsertId int64, err error) {
	s.searchCompany(ctx, req.Id)
	_, err = dao.LotCompany.Ctx(ctx).Where("id", req.Id).Update(req)
	return req.Id, err
}

// ExamineCompany 审核公司信息
func (s *sCompany) ExamineCompany(ctx context.Context, req *api.ExamineCompanyReq) (lastInsertId int64, err error) {
	s.searchCompany(ctx, req.Id)
	_, err = dao.LotCompany.Ctx(ctx).Where("id", req.Id).Update(req)
	return req.Id, err
}

// CompanyList 公司列表信息
func (s *sCompany) CompanyList(ctx context.Context, req *api.CompanyListReq) (res *model.CompanyListRes, err error) {
	findList := make([]*model.CompanyDetailsRes, 0)
	startNum, endNum := paging.Paging(req.Paging) // 获取分页偏移量
	searchInfo := g.Map{
		"company_status":      req.CompanyStatus,
		"company_name like ?": "%" + req.CompanyName + "%",
	}
	_ = dao.LotCompany.Ctx(ctx).OmitEmpty().Where(searchInfo).OrderDesc("created_at").Limit(startNum, endNum).Scan(&findList)
	// 获取总条数
	countNum, err := dao.LotCompany.Ctx(ctx).OmitEmpty().Where(searchInfo).Count()
	// 获取总页码
	PutPageList := paging.PutCount(req.Paging, countNum)
	res = &model.CompanyListRes{
		List:    findList,
		PutPage: *PutPageList,
	}
	return res, err
}

// searchCompany 判断有没有该公司
func (s *sCompany) searchCompany(ctx context.Context, Id int64) {
	r := g.RequestFromCtx(ctx)
	findOne, _ := dao.LotCompany.Ctx(ctx).Where("id", Id).One()
	if findOne == nil {
		response.JsonExit(r, consts.HTTPInternalServer.Code(), "没有该公司")
	}
	return
}
